package utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
	/**
	 * 数据源工具
	 */
	public class DataSourceUtils {
		public static DataSource dataSource = new ComboPooledDataSource();
		private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

		public static DataSource getDataSource() {
			return dataSource;
		}
		
		
		/**
		 * 从ThreadLocal中释放并且关闭Connection,并结束事务
		 * @throws SQLException
		 */
		public static void releaseAndCloseConnection() throws SQLException {
			Connection con = getConnection();
			if (con != null) {
				con.commit();
				tl.remove();
				con.close();
			}
		}
		/**
		 * 事务回滚
		 * @throws SQLException 
		 */
		public static void rollback() throws SQLException {
			Connection con = getConnection();
			if (con != null) {
				con.rollback();
			}
		}
}
	/**
	 * 开启事务
	 * @throws SQLException
	 */
	public static void startTransaction() {
		// TODO Auto-generated method stub
		Connection con = getConnection();
		if (con != null)
			con.setAutoCommit(false);
	}
	/**
	 * 当DBUtils需要手动控制事务时，调用该方法获得一个连接
	 * @return
	 * @throws SQLException
	 */
	
	private static Connection getConnection() throws SQLException{
		// TODO Auto-generated method stub
		Connection con = tl.get();
		if (con == null) {
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}
}